package cn.ad.server.web.spring.service.actions.handler;

import cn.ad.server.common.utils.BeanUtils;
import cn.ad.server.web.exception.AdServerMessageException;
import cn.ad.server.web.spring.model.sts.STSAdResponse;
import cn.ad.server.domain.ad.*;
import cn.ad.server.domain.enumration.MaterialFormat;
import cn.ad.server.domain.enumration.ReturnCode;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Random;

/**
 * @author dongbin.yu
 * @from 2016-06-25
 * @since V1.0
 */
public class DefaultAdFormatHandler extends AbstractAdFormatHandler {

    @Override
    public void matchCreative(AdSpace adSpace) {

        if (adSpace.getMatchStrategy() != null) {
//            List<Creative> creativeList = adSpace.getMatchStrategy().getCreatives();
            List<Creative> creativeList = adSpace.getMatchStrategy().getMatchCreatives();
            if (!CollectionUtils.isEmpty(creativeList)) {
                adSpace.setMatchCreative(creativeList.get(new Random().nextInt(creativeList.size())));
            }
        }
    }

    @Override
    public void compositeMaterial(AdSpace localAdSpace, STSAdResponse.AdSpace adSpace, int os) {

        Creative matchCreative = localAdSpace.getMatchCreative();
        AdMaterial adMaterial = localAdSpace.getMatchAdMaterial();

        //判断素材为空
        if (adMaterial == null) {
            throw new AdServerMessageException(ReturnCode.E20003);
        }

        //填充adResponse的adSpace数据
        STSAdResponse.Creative creative = new STSAdResponse.Creative();
        creative.setCid(matchCreative.getId());

        interactionHandler(matchCreative,creative, os);

        //填充印象对象
        String impressionTracking = matchCreative.getImpressionTracking();
        if (StringUtils.hasText(impressionTracking)) {
            creative.setImpression(impressionTracking.split("\\|\\|\\|"));
        }

        String clicksTracking = matchCreative.getClicksTracking();
        if (StringUtils.hasText(clicksTracking)) {
            creative.setClick(clicksTracking.split("\\|\\|\\|"));
        }

        // 设置广告位创意
        adSpace.setCreative(new STSAdResponse.Creative[] { creative });

        STSAdResponse.Banner banner = new STSAdResponse.Banner();
        AdSize adSize = adMaterial.getAdSize();
        banner.setWidth(adSize.getWidth());
        banner.setHeight(adSize.getHeight());
        banner.setCreativeUrl(BeanUtils.convertIosUrl(adMaterial.getMaterialUrl(), os));
        if (adMaterial.getMaterialFormat() > 0) {
            banner.setType(MaterialFormat.materialFormatMap.get(adMaterial.getMaterialFormat()).getName());
        }

        adSpace.getCreative()[0].setBanner(banner);
    }
}
